import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_rider/event/click_far_call_event.dart';
import 'package:flutter_rider/event/click_select_car_event.dart';
import 'package:flutter_rider/main/widgets/ext/u_shape.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/pop/pop_new_stations_list.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/module/task/page/task_detail_page.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/utils/status_utils.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main/page/far_call_page.dart';
import 'pop_stations_list.dart';

enum PopEnterType { 
     carManage, //车辆管理
     map,  //地图
}

class PopCarStatus extends StatefulWidget {
  int id;
  String title;

  PopEnterType type;

  PopCarStatus(this.id,this.type, {this.title = ""});

  @override
  State<StatefulWidget> createState() {
    return PopCarStatusState();
  }
}

class PopCarStatusState extends State<PopCarStatus> {
  dynamic _data;
  final StateLayoutController _stateLayoutController = StateLayoutController();
  bool _showDispatch = false;
  late StreamSubscription _eventFn1;
  late StreamSubscription _eventFn2;
  int _times = 0;
  late Timer _timer;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    initButton();
    _eventFn1 = eventBus.on<ChangeStationsEvent>().listen((event) {
      Navigator.of(context).pop();
      _stateLayoutController.reload();
    });
    _eventFn2 = eventBus.on<ClickFarCallEvent>().listen((event) {
      _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
        _countDown();
      });
    });
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      _countDown();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn1.cancel();
    _eventFn2.cancel();
    _timer.cancel();
    _recordLastSecond();
  }

  @override
  Widget build(BuildContext context) {
    var sw = MediaQuery.of(context).size.height;
    var height = sw * 0.7;

    if (MediaQuery.of(context).viewInsets.bottom > sw * 0.2) {
      height = sw * 0.9 - MediaQuery.of(context).viewInsets.bottom;
    }
    return Container(
        //height: height,
        margin: EdgeInsets.only(right: 10.rpx),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
        ),
        child:
        Column(
          children: [
            8.hspace,
            Container(
              width: 36.rpx,
              height: 5.rpx,
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.26),
                borderRadius: BorderRadius.circular(2.rpx),
              ),
            ),
            //isError?_renderErrorTitle():_renderTitle(),
            //isError?_renderErrorInfo():
            Expanded(
              child: StateLayout(
                url: "/car/detail?id=${widget.id}",
                controller: _stateLayoutController,
                childBuilder: _renderContent,
                dataCallback: (data) {
                  _data = data;
                },
              ),
            ),
          ],
        ),
    );
  }

  // Widget _renderErrorTitle() {
  //   String stText = "异常上报";
  //   return  Row(
  //       crossAxisAlignment: CrossAxisAlignment.center,
  //       children: [
  //         TextButton(onPressed: _onReturn,
  //             child: SvgPicture.asset(R.image_left, width: 24.rpx, height: 24.rpx),
  //         ),
  //         90.wspace,
  //         Expanded(
  //             child: UText.get(stText, Colors.black, 20.rpx, fw: FontWeight.bold)
  //         ),
  //       ]
  //   );
  // }

  Widget _renderTitle() {
    String stText = " ";
    if (_data != null) {
      if (_data["status"] == 3) {
        stText = " 任务中";
      } else if (_data["status"] == 2 || _data["status"] == 5) {
        stText = " 空闲中";
      } else if (_data["status"] == 4) {
        stText = " 调配中";
      }else if (_data["status"] == -1) {
        stText = " 不可用";
      }
    }
    return Container(
      height: 48.rpx,
      alignment: Alignment.center,
      child: UText.get(widget.title + stText, Colors.black, 20.rpx, fw: FontWeight.bold),
    );
  }

  Widget _renderContent(dynamic data) {
    _data = data;

    return SingleChildScrollView(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _renderTitle(),
        ..._renderCarInfo(),
        16.hspace,
        _getTaskTrack()
      ],
    ));
  }

  List<Widget> _renderCarInfo() {
    return [
      Row(
        children: [
          24.wspace,
          UText.get("当前模式", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          Expanded(
              child: UText.get(StatusUtils.getDriveMode(_data["drive_mode"]), Colors.black, 14.rpx)
          ),
          16.wspace,
          // _data["status"] == 3
          //   ?Container(
          //   margin: EdgeInsets.symmetric(horizontal: 16.rpx),
          //   child: TextButton(onPressed: _onClickUnusual,
          //       child: UText.get("异常", UIColor.color_none, 14.rpx)),
          // ):0.wspace
        ],
      ),
      12.hspace,
      Row(
        children: [
          24.wspace,
          UText.get("当前电量", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          UText.get("${_data["electricity"]}%", Colors.black, 14.rpx),
        ],
      ),
      12.hspace,
      // Row(
      //   children: [
      //     24.WSpace,
      //     UText.get("速度        ", Colors.black.withOpacity(0.4), 14.rpx),
      //     8.WSpace,
      //     UText.get("${_data["speed"]}m/s", Colors.black, 14.rpx),
      //   ],
      // ),
      // 12.HSpace,
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          _data["status"] == 4?
          Row(
            children: [
            UText.get("预计到达时间", Colors.black.withOpacity(0.4), 14.rpx),
            8.wspace,
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                UText.get(_data["estimate_time"].toString(), Colors.black, 14.rpx)
              ]
            )
          ])
          :
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              UText.get("车辆位置", Colors.black.withOpacity(0.4), 14.rpx),
              8.wspace,
              LimitedBox(
                maxWidth: 240.rpx,
                child: Text(_data["station"].toString(), style: TextStyle(color:Colors.black,fontSize: 14.rpx),overflow: TextOverflow.ellipsis,maxLines: 2),
              ),
          ])
      ])
    ];
  }

  Widget _getTaskTrack() {
    return Column(
      children: [
        _data["status"] == 3?_renderTaskLine() : 0.wspace,
        _data["status"] == -1?0.wspace:_renderBtn(),
      ],
    );
  }

  Widget _renderTaskLine() {
    int st = _data["waybill_operation"];
    if (st == 0 || st == -1) {
      return 0.hspace;
    }
    Widget rightWidget;
    if (st == -1) {
      rightWidget = UText.get("已取消", UIColor.color_t3, 14.rpx);
    } else if (st == 3) {
      rightWidget = UText.get("已完成", UIColor.color_t3, 14.rpx);
    } else {
      rightWidget = 0.wspace;
    }
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            color: UIColor.color_divider,
            height: 0.5.rpx,
            width: double.infinity,
            margin: EdgeInsets.symmetric(horizontal: 16.rpx),
          ),
          16.hspace,
          Padding(
            padding: EdgeInsets.only(left: 24.rpx),
            child: UText.get("任务路线", UIColor.color_t1, 16.rpx,textAlign:TextAlign.left,fw: FontWeight.w600),
          ),
          8.hspace,
          Row(
            children: [
              24.wspace,
              UText.getSubText("任务编号"),
              8.wspace,
              GestureDetector(
                onTap: () {
                  OpenUtils.open(context, TaskDetailPage(_data["waybill_mission_id"].toString()));
                },
                child: Text(
                  _data["waybill_mission_no"].toString(),
                  style: TextStyle(
                    fontSize: 14.rpx,
                    color: UIColor.color_primary,
                    decoration: TextDecoration.underline,
                    decorationColor: UIColor.color_primary,
                  ),
                ),
              ),
              8.wspace,
              rightWidget,
            ],
          ),
          10.hspace,
          _renderLoadWrap(),
          _renderUnLoadWrap()
        ]
    );
  }

  Widget _renderBtn() {
    return Container(
        margin: EdgeInsets.only(bottom:16.rpx),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _renderMessage(),
            (_data["status"] == 2 || _data["status"] == 5) && _showDispatch? _renderDispath() : 0.wspace,
            _data["status"] == 4 && _showDispatch? _renderChangeStation() : 0.wspace
          ],
        )
    );
  }

  Widget _renderMessage() {
    return  GestureDetector(
      onTap: () {
        OpenUtils.open(context, FarCallPage(widget.title,_data["car_id"].toString(), wmNo:_data["waybill_mission_no"].toString()));
      },
      child:Container(
        width: 140.rpx,
        height: 40.rpx,
        decoration: BoxDecoration(
        color: _data["status"] == 3?UIColor.color_primary:UIColor.color_content,
        border: Border.all(width: 1.rpx,color: _data["status"] == 3?UIColor.color_primary:const Color(0xffE7E7E7)),
        borderRadius: const BorderRadius.all(Radius.circular(60.0))
      ),child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SvgPicture.asset(_data["status"] == 3?R.image_message_white:R.image_message,width: 22.rpx,height: 22.rpx),
            4.wspace,
            UText.get("远程呼叫", _data["status"] == 3?UIColor.color_content:UIColor.color_t5, 15.rpx)
          ]
        )
      )
    );
  }

  Widget _renderDispath() {
    return GestureDetector(
        onTap: () {
          Navigator.pop(context);
          if (widget.type == PopEnterType.map){
              eventBus.fire(ClickSelectCarEvent(_data['lat'], _data['lng'], _data['car_no'], StatusUtils.getDriveMode(_data["drive_mode"]), _data["status"], _data["id"], 1,widget.type));
          }else{
              OpenUtils.pop4(context, PopNewStationsList(_data['lat'],_data['lng'],_data['car_no'],StatusUtils.getDriveMode(_data["drive_mode"]),_data["status"],_data["id"],1,widget.type));
          }
        },child: Container(
            width: 140.rpx,
            height: 40.rpx,
            margin: EdgeInsets.only(left:16.rpx),
            decoration: const BoxDecoration(
            color: UIColor.color_primary,
            borderRadius: BorderRadius.all(Radius.circular(60.0))
          ),child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SvgPicture.asset(R.image_dispatch,width: 22.rpx,height: 22.rpx),
                4.wspace,
                UText.get("开始调车", UIColor.color_content, 15.rpx)
              ]
          )
        )
    );
  }

  Widget _renderChangeStation() {
    return GestureDetector(
            onTap: () {
              OpenUtils.pop2(context, PopStationsList(_data['lat'],_data['lng'],_data['car_no'],StatusUtils.getDriveMode(_data["drive_mode"]),_data["status"],_data["id"],2));
            },
            child:Container(
                width: 140.rpx,
                height: 40.rpx,
                margin: EdgeInsets.only(left:16.rpx),
                decoration: const BoxDecoration(
                color: UIColor.color_primary,
                borderRadius: BorderRadius.all(Radius.circular(60.0))
            ),child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    SvgPicture.asset(R.image_dispatch,width: 22.rpx,height: 22.rpx),
                    4.wspace,
                    UText.get("变更终点", UIColor.color_content, 15.rpx)
                  ]
              )
          )
      );
  }

  Widget _renderLoadWrap() {
    int st = _data["waybill_operation"];
    int ms = _data["mission_status"];
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          Column(
            children: [
              4.hspace,
              UShape.getCircle(
                  size: 12.rpx, color: ms >= 3? UIColor.color_primary : UIColor.color_content, borderColor: UIColor.color_primary, borderWidth: 1.rpx),
              Expanded(
                child: Container(
                  width: 1.rpx,
                  color: st == 2 || ms >= 5? UIColor.color_primary : const Color(0xffd2d2d2),
                ),
              ),
            ],
          ),
          10.wspace,
          _renderLoad(),
          4.wspace,
        ],
      ),
    );
  }

  Widget _renderUnLoadWrap() {
    int st = _data["waybill_operation"];
    int ms = _data["mission_status"];
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          Column(
            children: [
              Container(
                height: 4.rpx,
                width: 1.rpx,
                color: st == 2 || ms >= 5? UIColor.color_primary : const Color(0xffd2d2d2),
              ),
              UShape.getCircle(
                  size: 12.rpx,
                  color: ms == 7? UIColor.color_primary : UIColor.color_content,
                  borderColor: st == 2 ? UIColor.color_primary : const Color(0xffd2d2d2),
                  borderWidth: 1.rpx),
            ],
          ),
          10.wspace,
          _renderUnload(),
          4.wspace,
        ],
      )
    );
  }

  Widget _renderLoad() {
    int ms = _data["mission_status"];
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderKv("发货地址", "pick_station_name", ms >= 3 ? UIColor.color_primary : UIColor.color_t1 ),
          5.hspace,
          _renderKv("发货人    ", "pick_username", UIColor.color_t1),
          5.hspace,
          _renderKv("发货电话", "pick_tel", UIColor.color_t1),
          5.hspace,
          _renderKv("发货车牌", "pick_car_plate", UIColor.color_t1),
          14.hspace,
        ],
      ),
    );
  }

  Widget _renderUnload() {
    int ms = _data["mission_status"];
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _renderKv("收货地址", "delivery_station_name", ms == 7 ? UIColor.color_primary : UIColor.color_t1),
          5.hspace,
          _renderKv("收货人    ", "delivery_username", UIColor.color_t1),
          5.hspace,
          _renderKv("收货电话", "delivery_tel", UIColor.color_t1),
          5.hspace,
          _renderKv("收货车牌", "delivery_car_plate", UIColor.color_t1),
          24.hspace,
        ],
      ),
    );
  }

  Widget _renderKv(String key, String value, Color color) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        UText.getSubText(key),
        12.wspace,
        Expanded(
          child: UText.get(_data[value], color, 14.rpx, fw: FontWeight.w600),
        ),
      ],
    );
  }

  _countDown() async {
    var _sp = await SharedPreferences.getInstance();
    _times = _sp.getInt("_second") ?? 0;
    print(_times);
    if( _times > 0) {
      _times -= 1;
      _sp.setInt("_second",_times);
    } else {
      _timer.cancel();
      _times = 0;
      _sp.setInt("_second",0);
    }
  }

  _recordLastSecond() async {
    var _sp = await SharedPreferences.getInstance();
    _sp.setInt("_second", _times);
  }

  initButton() async {
    var _sp = await SharedPreferences.getInstance();
    _showDispatch = _sp.getBool("_showDispatch") as bool;
  }
}
